package coderx

import (
	"fmt"
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/datax/jsonmap"
	"gitee.com/zhongguo168a/gocodes/datax/reflectx"
	"gitee.com/zhongguo168a/gocodes/datax/schemax"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
)

func AnyToMap(document interface{}) (map[string]interface{}, error) {
	switch d := document.(type) {
	case map[string]interface{}:
		return d, nil
	case reflectx.IRefObject:
		schema := schemax.GetDeclByKey(d.RefType())
		m := map[string]interface{}{}
		if schema == nil {
			err := jsonmap.StructToMap(d, m)
			if err != nil {
				err = errorx.Wrap(err, fmt.Sprintf("jsonmap.StructToMap"), datax.M{"document": document})
				return nil, err
			}
		} else {
			err := NewRefToMap().SetSource(d).Write(m)
			if err != nil {
				err = errorx.Wrap(err, "MapToRef.Write")
				return nil, err
			}
		}

		return m, nil
	default:
		m := map[string]interface{}{}
		err := jsonmap.StructToMap(d, m)
		if err != nil {
			err = errorx.Wrap(err, fmt.Sprintf("jsonmap.StructToMap"), datax.M{"document": document})
			return nil, err
		}

		return m, nil
	}
}
